<script setup lang="ts">
import { nextTick, ref } from 'vue'
import { ElMessage, ElUpload, type UploadRawFile } from 'element-plus'
import { ArrowRight, Plus } from '@element-plus/icons-vue'

import Editor from '@/views/publish/QuillEditor.vue'
import { getChannel } from '@/apis/stores/article'
import type { PublishArticleAPI } from '@/types/publish'
import { uploadImage } from '@/apis/stores/publish'

const props = defineProps({
  content: { type: String, default: '' },
  readOnly: { type: Boolean, default: false },
  fileSize: { type: Number, default: 10 },
})

const uploadUrl = ref(import.meta.env.VITE_BASEURL + '/sysFiles/upload')

function handleBeforeUpload(file: File) {
  const type = ['image/jpeg', 'image/jpg', 'image/png']
  const isJPG = type.includes(file.type)
  if (!isJPG) {
    ElMessage.error('图片格式错误！只能上传jpeg/jpg/png格式')
    return false
  }
  if (props.fileSize && file.size / 1024 / 1024 > props.fileSize) {
    ElMessage.error(`上传文件大小不能超过 ${props.fileSize} MB!`)
    return false
  }
  return true
}

function handleUploadError() {
  ElMessage.error('图片插入失败')
}
// 频道选项数组 (用于渲染)
const channelOptions = ref([{ id: '0', name: '推荐' }])

// 获取所有频道列表
const AllChannel = async () => {
  try {
    const res = await getChannel()
    console.log('channel', res.data.channels)
    // 将后台数据赋值给数组
    channelOptions.value = res.data.channels
  } catch (err) {
    console.log('错误信息：', err)
  }
}
AllChannel()

// 发表文章请求数据
const PublishArticleParams = ref<PublishArticleAPI>({
  title: '',
  content: '',
  cover: {
    type: '1',
    images: [],
  },
  channel_id: 0,
})

// 覆盖默认的上传行为，可以实现自定义上传
const uploadFile = async (obj: { file: UploadRawFile }) => {
  const fd = new FormData()
  fd.append('image', obj.file)
  const res = await uploadImage(fd)
  console.log('res', res)
  PublishArticleParams.value.cover.images.push(res.data.url)
}

const uploadRef = ref<InstanceType<typeof ElUpload> | null>(null)
// 封面变化
const changeCoverType = async () => {
  await nextTick()
  if (uploadRef.value) {
    // 清空已经上传的文件列表
    uploadRef.value.clearFiles()
    // 清空封面数组
    PublishArticleParams.value.cover.images = []
  } else {
  }
}
</script>

<template>
  <el-card>
    <!-- 导航部分 -->
    <template #header>
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>发布文章</el-breadcrumb-item>
      </el-breadcrumb>
    </template>
    <!-- 内容部分 -->
    <div class="form">
      <el-form class="">
        <el-form-item label="标题：" style="width: 450px">
          <el-input placeholder="请输入标题" v-model="PublishArticleParams.title"></el-input>
        </el-form-item>
        <el-form-item label="频道：">
          <el-select
            v-model="PublishArticleParams.channel_id"
            style="width: 240px"
            placeholder="请选择频道"
            clearable
          >
            <el-option
              v-for="item in channelOptions"
              :value="item.id"
              :label="item.name"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 封面部分 -->
        <el-form-item label="封面：">
          <el-radio-group v-model="PublishArticleParams.cover.type" @change="changeCoverType">
            <el-radio value="1" label="单图"></el-radio>
            <el-radio value="3" label="三图"></el-radio>
            <el-radio value="0" label="无图"></el-radio>
            <el-radio value="-1" label="自动"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-upload
          ref="uploadRef"
          :limit="Number(PublishArticleParams.cover.type)"
          v-if="PublishArticleParams.cover.type === '1' || PublishArticleParams.cover.type === '3'"
          :show-file-list="true"
          list-type="picture-card"
          :http-request="uploadFile"
        >
          <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="editorBox" style="height: 300px">
          <el-upload
            :action="uploadUrl"
            :before-upload="handleBeforeUpload"
            :on-error="handleUploadError"
            :show-file-list="false"
            class="editor-img-uploader"
            accept=".jpeg,.jpg,.png"
          >
            <i ref="uploadRef" class="el-icon-plus editor-img-uploader"></i>
          </el-upload>

          <Editor v-model="PublishArticleParams.content" />
        </div>
        <el-form-item style="margin-top: 75px">
          <el-button type="primary">发布文章</el-button>
          <el-button>存入草稿</el-button>
          {{ PublishArticleParams }}
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>
<style scoped>
.form {
  margin-left: 25px;
}
</style>
